package com.xm.jasypt.generator;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * @author yousj
 * @since 2021/10/15
 */
public class EncryptorUtil {

    /**
     * Jasypt生成加密结果
     *
     * @param salt  配置文件中设定的加密盐值
     * @param value 加密值
     * @return
     */
    public static String encyptPwd(String salt, String value) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(cryptor(salt));
        return encryptor.encrypt(value);
    }

    /**
     * 解密
     *
     * @param salt  配置文件中设定的加密盐值
     * @param value 解密密文
     * @return
     */
    public static String decyptPwd(String salt, String value) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(cryptor(salt));
        return encryptor.decrypt(value);
    }

    public static SimpleStringPBEConfig cryptor(String salt) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(salt);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        return config;
    }

    public static void main(String[] args) {
        String encPwd = encyptPwd("xx", "root");
        String decPwd = decyptPwd("xx", encPwd);
        System.out.println(encPwd);
        System.out.println(decPwd);
    }
}
